package org.yunai.yfserver.event;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 事件分发者
 * User: yunai
 * Date: 13-5-11
 * Time: 上午12:43
 */
public class EventDispatcher {

    /**
     * 监听者集合
     */
    private Map<Class<? extends IEvent>, List<IEventListener>> listeners = new HashMap<Class<? extends IEvent>, List<IEventListener>>(1);

    /**
     * 注册事件监听者
     *
     * @param eventClazz 事件
     * @param listener 监听者
     */
    public <E extends IEvent> void register(Class<E> eventClazz, IEventListener listener) {
        List<IEventListener> subListeners = listeners.get(eventClazz);
        if (subListeners == null) {
            listeners.put(eventClazz, subListeners = new ArrayList<IEventListener>(1));
        }
        for (IEventListener subListener : subListeners) {
            if (subListener.getClass().equals(eventClazz.getClass())) {
                throw new IllegalArgumentException("Event[" + eventClazz.getClass() + "] register Listener[" + eventClazz.getComponentType() + "] already..");
            }
        }
        subListeners.add(listener);
    }

    /**
     * 通知监听者们
     *
     * @param event 事件
     */
    @SuppressWarnings("unchecked")
    public <E extends IEvent> void fireEvent(E event) {
        List<IEventListener> subListeners = listeners.get(event.getClass());
        if (subListeners == null || subListeners.isEmpty()) {
            return;
        }
        for (IEventListener subListener : subListeners) {
            subListener.fireEvent(event);
        }
    }
}
